﻿using System;
using System.Collections.Generic;

namespace ConsoleApp.拦截器
{
    public class BusinessChainBuilder<TBusinessChain, TPluginContext>
        where TBusinessChain : AbstractBusinessChain<TPluginContext>
    {
        private readonly List<Action<TPluginContext, Action<TPluginContext>>> _plugins;
        public BusinessChainBuilder()
        {
            _plugins = new List<Action<TPluginContext, Action<TPluginContext>>>();
        }

        /// <summary>
        /// 构建业务链
        /// </summary>
        /// <returns></returns>
        public TBusinessChain Build()
        {
            Action<TPluginContext> action = c => { };

            _plugins.Reverse();
            var plugins = _plugins.GetEnumerator();
            while (plugins.MoveNext())
            {
                var next = action;
                var plugin = plugins.Current;
                action = c => plugin?.Invoke(c, next);
            }
            var instanse = Activator.CreateInstance(typeof(TBusinessChain), new[] { action });
            return (TBusinessChain)instanse;
        }


        /// <summary>
        /// 添加插件
        /// </summary>
        /// <param name="plugin"></param>
        public void AddPlugin(Action<TPluginContext, Action<TPluginContext>> plugin)
        {
            if (plugin == null) throw new ArgumentNullException(nameof(plugin));

            _plugins.Add(plugin);
        }
    }
}